package com.ycsj.goldmedalnewconcept.student.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.base.BaseLazyFragment;
import com.ycsj.common.base.SpKeys;
import com.ycsj.common.manager.BannerManager;
import com.ycsj.common.utils.SPUtil;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.common.view.scroll.MyGridView;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.WxAppUtils;
import com.ycsj.goldmedalnewconcept.common.activity.ScanQrCodeActivity;
import com.ycsj.goldmedalnewconcept.common.adapter.HomeGvAdapter;
import com.ycsj.goldmedalnewconcept.common.bean.HomeInfo;
import com.ycsj.goldmedalnewconcept.common.http.HttpCallBack;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.common.util.LpUtils;
import com.ycsj.goldmedalnewconcept.student.activity.ChooseStudentUnitActivity;
import com.ycsj.goldmedalnewconcept.student.activity.MyHomeWorkActivity;
import com.ycsj.goldmedalnewconcept.student.activity.StudentMyHomeActivity;
import com.ycsj.goldmedalnewconcept.student.bean.BannerInfo;
import com.youth.banner.Banner;
import com.youth.banner.Transformer;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 学生端主界面Fragment
 * Created by Administrator on 2019/2/19 0019.
 */

public class StudentHomeFragment extends BaseLazyFragment implements AdapterView.OnItemClickListener {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.rl_loading)
    RelativeLayout rlLoading;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.lv_edit)
    ImageView lvEdit;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.gv)
    MyGridView mGv;
    @BindView(R.id.lv_cw)
    ImageView lvCw;

    //首页的展示的条目的数据集合
    private List<HomeInfo> homeInfos;

    //适配器对象
    private HomeGvAdapter adapter;


    //首页的栏目名称
//    private String[] itemNames = {"金牌新概念1", "我的练习", "我的测评"};


//    private final String[] itemNames = {"金牌新概念1", "我的练习", "金牌新概念Ai"};

    private final String[] itemNames = {"金牌新概念1", "我的练习"};


    //首页的栏目的所有图片
//    private int[] itemResId = {R.drawable.student_jpxjl, R.drawable.student_zy, R.drawable.student_cp};
//    private final int[] itemResId = {R.drawable.student_jpxjl, R.drawable.student_zy, R.drawable.jpj_work};
    private final int[] itemResId = {R.drawable.student_jpxjl, R.drawable.student_zy};


    //宠物对应的发呆  0狗 1怪物 2老虎 3大象
    private final int[] gif_fd = {R.drawable.xg_fd, R.drawable.xgw_fd, R.drawable.xlh_fd, R.drawable.xx_fd};

    //轮播图数据
    private List<String> defaultImgs;

    //请求的参数
    private String acc, role, apptoken, schoolid, province, city, area;


    public static final String TAG = StudentHomeFragment.class.getName();

    //单体模式
    private static class LazyHolder {
        private static final StudentHomeFragment INSTANCE = new StudentHomeFragment();
    }

    public static final StudentHomeFragment newInstance() {
        return LazyHolder.INSTANCE;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_student_home;
    }

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {

    }

    @Override
    protected void init(View view, Bundle savedInstanceState) {
        super.init(view, savedInstanceState);

        //初始化标题栏
        initTitle();

        //根据学生的宠物类型设置宠物
        initPet();

        //模拟请求参数
        initParams();

        //初始化数据
        initData();

        //初始化列表
        initGv();

        //请求轮播图的数据
        httpBanner();
    }

    /**
     * 根据学生选择的宠物类型设置宠物
     */
    private void initPet() {
        int index = 0;
        String petType = SPUtil.getString(getContext(), SpKeys.SERVICEPETTYPE);
        if (!TextUtils.isEmpty(petType)) {
            index = Integer.parseInt(petType);
            if (index == -1) {
                index = 0;
            }
        }
        Glide.with(getContext()).load(gif_fd[index]).into(lvCw);
    }

    /**
     * 配置请求参数
     */
    private void initParams() {
        acc = AccountUtils.getAccount(getContext());
        role = AccountUtils.getRole(getContext());
        apptoken = AccountUtils.getToken(getContext());
        schoolid = AccountUtils.getSchoolId(getContext());
        province = SPUtil.getString(getContext(), SpKeys.PROVINCE);
        city = SPUtil.getString(getContext(), SpKeys.CITY);
        area = SPUtil.getString(getContext(), SpKeys.AREA);
    }


    /**
     * 请求轮播图的数据
     */
    private void httpBanner() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "1");
        map.put("acc", acc);
        map.put("role", role);
        map.put("apptoken", apptoken);
        map.put("platform", "2");
        map.put("province", province);
        map.put("city", city);
        map.put("area", area);
        map.put("schoolid", schoolid);

        Log.i("test", "province=" + province + "&city=" + city + "&area=" + area + "&schoolid=" + schoolid +
                "&apptoken=" + apptoken);

        HttpUtils.post(HttpAddress.BANNERDATA, map, this, new HttpCallBack<BannerInfo>() {
            @Override
            public void onSuccess(BannerInfo bannerInfo) {
                rlLoading.setVisibility(View.GONE);
                banner.setVisibility(View.VISIBLE);
                if (bannerInfo.getState().equals("200")) {
                    BannerInfo.DataBean data = bannerInfo.getData();
                    if (data != null) {
                        //设置轮播图的数据
                        initBanner(data);
                    }

                } else {
                    ToastUtils.showShort(BaseApplication.STATEERROE + bannerInfo.getState());
                }

            }

            @Override
            public void onError(String e) {
                rlLoading.setVisibility(View.GONE);
                ToastUtils.showShort(BaseApplication.ERROR);
            }
        });

    }


    /**
     * 初始化标题栏
     */
    private void initTitle() {
        ivBack.setVisibility(View.INVISIBLE);
        tvTitle.setText("金牌君");

        //二维码的扫描框
        RelativeLayout.LayoutParams lp = LpUtils.getRelatLp(UiUtils.dp2px(36), UiUtils.dp2px(36));
        lp.addRule(RelativeLayout.CENTER_IN_PARENT);
        lvEdit.setLayoutParams(lp);
        lvEdit.setImageResource(R.drawable.sacn_img);
        lvEdit.setVisibility(View.VISIBLE);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        homeInfos = new ArrayList<>();
        for (int i = 0; i < itemNames.length; i++) {
            HomeInfo info = new HomeInfo();
            info.resId = itemResId[i];
            info.name = itemNames[i];
            homeInfos.add(info);
        }
    }

    /**
     * 初始化列表的方法
     */
    private void initGv() {
        adapter = new HomeGvAdapter(getContext(), homeInfos, R.layout.gv_home);
        mGv.setAdapter(adapter);
        mGv.setOnItemClickListener(this);
    }

    /**
     * 设置Banner的数据
     */
    private void initBanner(BannerInfo.DataBean data) {
        String picUrls = data.getPicture();
        if (!TextUtils.isEmpty(picUrls)) {
            defaultImgs = new ArrayList<>();
            String[] urls = picUrls.split("￠");
            Collections.addAll(defaultImgs, urls);
            BannerManager.setData(banner, true, defaultImgs, Transformer.ZoomOut);
        }
    }


    /**
     * 条目点击事件
     *
     * @param adapterView
     * @param view
     * @param pos         点击的位置
     * @param l
     */
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {

        if (!isDoubleClick(view)) {
            switch (pos) {
                case 0:
                    //金牌新概念1
                    UiUtils.startActivity(getActivity(), ChooseStudentUnitActivity.class);
                    break;
                case 1:
                    //跳转到学生端我的练习界面
                    UiUtils.startActivity(getActivity(), MyHomeWorkActivity.class);
                    break;
                case 2:
                    //跳转金牌单词王小程序
                    WxAppUtils.launchWeApp(getContext());
                    break;
            }
        }
    }

    /**
     * 点击事件
     */
    @OnClick({R.id.lv_cw, R.id.lv_edit})
    public void onClickView(View v) {
        if (!isDoubleClick(v)) {
            switch (v.getId()) {
                case R.id.lv_cw:
                    //宠物,跳转到我的家界面
                    UiUtils.startActivity(getContext(), StudentMyHomeActivity.class);
                    break;
                case R.id.lv_edit:
                    //二维码扫描界面
                    UiUtils.startActivity(getContext(), ScanQrCodeActivity.class);
                    break;
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        if (null != banner) {
            banner.startAutoPlay();
        }

    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
        if (null != banner) {
            banner.stopAutoPlay();
        }
    }

}
